<?php

namespace App\Http\Controllers\v1;

use App\Http\Resources\WatchCollection;
use App\Models\Watch;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class WatchController extends Controller
{
    //记录用户的观看记录
    public function recording(Request $request, int $id)
    {
        $classid = $request->get('classid');
        if (is_null($classid)) return ['status' => 1, 'msg' => '参数错误'];
//        先删除符合条件的，再添加
        Watch::where(['student_id' => $id, 'class_id' => $classid])->delete();
        $res = Watch::create(['student_id' => $id, 'class_id' => $classid]);
        if ($res) return ['status' => 0, 'msg' => '成功'];
        return ['status' => 1, 'msg' => '失败'];
    }

    /**
     * 获取历史记录
     * 可选参数 offset limit
     * @param Request $request
     * @param int $id 学生id
     * @return WatchCollection
     */
    public function history(Request $request, int $id)
    {
        $offset = $request->get('offset', 0);
        $limit = $request->get('limit', 5);
        $limit = min(max($limit, 1), 20);
        $data = Watch::with('classes')
            ->where('student_id', $id)
            ->orderBy('created_at', 'desc')
            ->offset($offset)
            ->limit($limit)
            ->get();
        return new WatchCollection($data);
    }
}
